/**
* @description: 738. 单调递增的数字
* @author hewei
* @date 2022/8/13 14:34
* @version 1.0
*/

public class MonotoneIncreasingDigits {

    public static void main(String[] args) {
        MonotoneIncreasingDigits monotoneIncreasingDigits = new MonotoneIncreasingDigits();
        System.out.println(monotoneIncreasingDigits.monotoneIncreasingDigits(100));
    }

    public int monotoneIncreasingDigits(int n) {
        char[] chars = (n + "").toCharArray();
        for (int i = 1; i < chars.length; i++) {
            if (chars[i] >= chars[i - 1]) continue;
            int index = i - 1;
            while (index > 0 && chars[index] - 1 < chars[index - 1]) --index;
            chars[index] -= 1;
            for (int k = index + 1; k < chars.length; k++) {
                chars[k] = '9';
            }
            break;
        }
        return Integer.parseInt(new String(chars));
    }
}
